import 'package:flutter/material.dart';
import 'package:proj_sfv/http/requests.dart';

class ChooseBookmarkDialog extends StatefulWidget {
  @override
  _ChooseBookmarkDialogState createState() => _ChooseBookmarkDialogState();

  String token;
  int id;

  ChooseBookmarkDialog(this.id, this.token);
}

class _ChooseBookmarkDialogState extends State<ChooseBookmarkDialog> {
  List<String> _bookmarks = [];

  String _selectedBookmark;

  final _newBookmarkController = TextEditingController();


  @override
  void initState() {
    getMyCategoryListRequest(context, widget.id, widget.token).then((value) {
      if (value != null) {
        if (value.isEmpty) {
          setState(() {
            _bookmarks.add("默认");
          });
        } else {
          setState(() {
            _bookmarks.addAll(value);
          });
        }
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    _newBookmarkController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text('选择收藏夹'),
      content: Container(
        width: double.maxFinite,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: _newBookmarkController,
              decoration: InputDecoration(
                hintText: '新收藏夹',
              ),
            ),
            SizedBox(height: 16),
            ListView.builder(
              shrinkWrap: true,
              itemCount: _bookmarks.length,
              itemBuilder: (context, index) {
                final bookmark = _bookmarks[index];
                return ListTile(
                  leading: Icon(Icons.bookmark),
                  title: Text(bookmark),
                  onTap: () {
                    setState(() {
                      _selectedBookmark = bookmark;
                    });
                  },
                  selected: _selectedBookmark == bookmark,
                );
              },
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('取消'),
        ),
        TextButton(
          onPressed: () {
            final newBookmarkName = _newBookmarkController.text.trim();
            if (newBookmarkName.isNotEmpty) {
              Navigator.pop(context, newBookmarkName);
            } else {
              Navigator.pop(context, _selectedBookmark);
            }
          },
          child: Text('确认'),
        ),
      ],
    );
  }
}

